package com.dwin.dingnuo.utils;

import android.text.TextUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * 加密工具类
 */
public class EncryptUtils {

    /**
     * md5加密字符串 eg：123456 加密后结果 md5e10adc3949ba59abbe56e057f20f883e
     * @param string
     * @return
     */
    public static String md5(String string) {
        if (TextUtils.isEmpty(string)) {
            return "";
        }
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            byte[] bytes = md5.digest(string.getBytes());
            String result = "";
            for (byte b : bytes) {
                String temp = Integer.toHexString(b & 0xff);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                result += temp;
            }
            return result;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static final String secretKey = "8p0U52M";

    /**
     * 根据请求的map，返回sign值
     * @param map
     * @return
     */
    public static String getSign(Map<String, String> map) {
        Map<String, String> sortByKeyResultMap = sortMapByKey(map); // 按Key进行排序
        String values = orderedValues(sortByKeyResultMap) + secretKey;
        System.out.println("md5之前的:"+  values);
        String md5 = md5(values.toLowerCase());
        System.out.println("md5之后的:"+  md5);
        return md5;
    }

    /**
     * 已经排序的值的map
     *
     * @param map
     * @return
     */
    public static String orderedValues(Map<String, String> map) {
        Iterator<Map.Entry<String, String>> sortByKeyEntries = map.entrySet().iterator();
        StringBuffer sb = new StringBuffer();
        while (sortByKeyEntries.hasNext()) {
            Map.Entry<String, String> entry = sortByKeyEntries.next();
            System.out.println("md5 Key = " + entry.getKey() + "------->Value = " + entry.getValue());
            sb.append(entry.getValue());
        }
        System.out.println( sb.toString());
        return sb.toString();
    }

    /**
     * 使用 Map按key进行排序
     *
     * @param map
     * @return
     */
    public static Map<String, String> sortMapByKey(Map<String, String> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
            public int compare(String obj1, String obj2) {
                return obj1.compareTo(obj2);// 升序排序
            }
        });
        sortMap.putAll(map);
        return sortMap;
    }

}
